<?

class ReleaseTrack extends db {
	
	var $ID, $title, $meta_information, $lyrics, $length, $release_id, $number, $audio_file, $av_area_id;
	
	function getID() { return $this->ID; }
	function getMetaInformation() {return $this->meta_information;}
	function getLyrics() {return $this->lyrics;}
	function getTitle() {return $this->title;}
	function getLength() {
		$length = date('i:s', strtotime($this->length));
		if (strlen($length) > 0) {
			if (substr($length, 0, 1) == '0') {
				$length = substr($length, 1);
			}
		}
		
		return $length;
	}
	function lengthSet() {
		return ($this->length != null);
	}
	function getReleaseID() {return $this->release_id;}
	function getReleaseObject() {
		$r = Release::get($this->release_id);
		return $r;
	}
	function getNumber() {return $this->number;}
	function getAudioFile() {return $this->audio_file;}
	function isValidAudioFile() {
		if ($this->getAudioFile() != null && $this->getAudioFile() != '') {
			$filesize = $this->getAudioFileSize();
			return $filesize > 0;
		}
		return Error::create("Unable to read audio track or audio track does not exist.");
	}
	function getAudioFileSize() {
		if (file_exists(AUDIO_DIRECTORY . '/' . $this->getAudioFile())) {
			$file = AUDIO_DIRECTORY . '/' . $this->getAudioFile();
			return filesize($file);
		}
	}
	function getAVAreaID() {return $this->av_area_id;}
	function getAVAreaObject() {
		if ($this->av_area_id > 0) {
			$ma = MediaArea::get($this->av_area_id);
			return $ma;
		} else {
			$e = new Error();
			$e->add("An administrator has not yet registered this track for audio or videos.");
			return $e;
		}
	}	
	function get($trackID) {
		if (is_numeric($trackID) && $trackID > 0) {
			$q = "select * from Release_Tracks where ID = " . $trackID;
			$db = new db;
			$r = mysql_query($q);
			if (!$r) {
				return Error::MySQL();
			}
			
			$row = mysql_fetch_assoc($r);
			if ($row['ID']) {				
				$re = new ReleaseTrack;
				$re->ID = $row['ID'];
				$re->title =  db::sanitize_from_db($row['title']);
				$re->meta_information =  db::sanitize_from_db($row['meta_information']);
				$re->lyrics = db::sanitize_from_db($row['lyrics']);
				$re->length = $row['length'];
				$re->release_id = $row['release_id'];
				$re->number = $row['number'];
				$re->audio_file = $row['audio_file'];
				$re->av_area_id = $row['av_area_id'];
				return $re;
			}
		}
		
		return Error::create("Invalid track ID.");
	}
	
	function getByAudio($filename) {
		$audio_file = $this->sanitize_to_db($filename);
		$q = "select ID from Release_Tracks where filename = '{$filename}'";
		$r = mysql_query($r);
		if (!$r) {
			return Error::MySQL();
		}
		$row = mysql_fetch_assoc($r);
		$rt = ReleaseTrack::get($row['ID']);
		return $rt;
	}
	
	function update($postArray) { 
		$db = new db;
		if (User::isAdmin()) {
			$title = $db->sanitize_to_db($postArray['title']);
			$number = $db->sanitize_to_db($postArray['number']);
			$length = $db->sanitize_to_db($postArray['length']);
			if ($postArray['length'] != "") {
				$length = $db->sanitize_to_db($postArray['length']);
				$length = "'00:{$length}'";
			} else {
				$length = "null";
			}

			$meta_information = $db->sanitize_to_db($postArray['meta_information']);
			$lyrics = $db->sanitize_to_db($postArray['lyrics']);
			
			if (!$title) {
				$title = '(untitled track)';
			}
			
			$r = @mysql_query("update Release_Tracks set title='$title', number='$number', meta_information = '$meta_information', lyrics = '$lyrics', length = {$length} where ID = {$this->ID}");
			if (!$r) {
				return Error::MySQL();
			} else {
				return ReleaseTrack::get($this->ID);
			}
		} else {
			return Error::create("You are not allowed to update tracks.");
		}
	}
	
	// add() moved into Releases, where it makes more sense
	
	function remove() { 
		if (User::isAdmin()) {
			$r = @mysql_query("delete from Release_Tracks where ID = '{$this->ID}'");
			if (!$r) {
				return Error::MySQL();
			} else {
				$re = Release::get($this->release_id);
				return $re;
			}
		} else {
			return Error::create("YOu are not allowed to remove tracks.");
		}
	}
		
	
	function addAudioIncoming($file) {
		$res = $this->validateTrackAudio('add');
		if (db::isError($res)) {
			return $res;
		}
		
		$new_file = $this->generateAudioFilename($file);
		
		$orig_path = SITE_FULL_DIRECTORY . MEDIA_INCOMING_DIRECTORY . '/' . $file;
		$new_path = AUDIO_DIRECTORY . '/' . $new_file;
		$res1 = @copy($orig_path, $new_path);
		if (!$res1) {
			return Error::create("Unable to copy file to directory: " . $new_path);
			return $e;
		}
	
		if (file_exists($new_path)) {
			// success!
			$q = "update Release_Tracks set audio_file = '$new_file' where ID = '{$this->ID}'";
			$r = mysql_query($q);
			if ($r) {
				return $r;
			} else {
				return Error::MySQL();
			}
		} else {
			return Error::create("Unable to create file.");
		}
	}
	
	function addAudioRemote($url) {
		$res = $this->validateTrackAudio('add');
		if (db::isError($res)) {
			return $res;
		}
					
		$filename = basename($url);
		$new_file = $this->generateAudioFilename($filename);
		$file = fopen($url, 'r');
		if (!$file) {
			return Error::create("Unable to open file at location: " . $url);
		}
		
		while (!feof($file)) {
			$tempfile .= fread($file, 4096);
		}
			
		if (!file_exists(AUDIO_DIRECTORY . '/' . $new_file)) {
			$fp = fopen(AUDIO_DIRECTORY . '/' . $new_file, 'wb');
			fputs($fp, $tempfile, strlen($tempfile));
			fclose($fp);
		} else {
			return Error::create("Unable to create file at location: " . $new_file);
		}
			
		if (file_exists(AUDIO_DIRECTORY . '/' . $new_file)) {
			// success!
			$q = "update Release_Tracks set audio_file = '$new_file' where ID = '{$this->ID}'";
			$r = mysql_query($q);
			if ($r) {
				return $r;
			} else {
				return Error::MySQL();
			}
		}
	}
	
	function removeAudio() {
		$res = $this->validateTrackAudio('remove');
		if (db::isError($res)) {
			return $res;
		}
		
		$track = AUDIO_DIRECTORY . '/' . $this->audio_file;
		$q = "update Release_Tracks set audio_file = null where ID = '{$this->ID}'";
		if (file_exists($track)) {
			$r1 = unlink($track);
			if (!$r1) {
				return Error::create("Unable to remove file: " . $track);
			}
		}
		
		$r = mysql_query($q);
		
		if ($r) {
			return $r;
		} else {
			return Error::MySQL();
		}
	}
	
	function validateTrackAudio($operation) {
		if (User::isAdmin()) {
			switch($operation) {
				case 'add':
					if ($this->audio_file != "" || $this->audio_file != null) {
						return Error::create('There already exists a registered audio file for this track.');
					}
					break;
				case 'remove':
					if ($this->audio_file == "" || $this->audio_file == null) {
						return Error::create('There is no record of an audio file for this track.');
					}
					break;
			}
		
		} else {
			return Error::create('You are not allowed to modify track audio.');
		}
		
		// if we get down here, then we return true, because the subroutines found nothing wrong
		return true;		
	}
	
	function generateAudioFilename($filename) {
		// takes a track ID, generates a unique audio filename that makes sense for that track
		// compilation of track name w/underscores, track number, and a random number (if necessary)
		// we assume the track ID is valid
		require_once(CLASSES . '/m2.php');
		$title = $this->getNumber() . '_' . Media::sanitizeFile($this->getTitle()) . '.' . Media::getExtension($filename);
		
		if (file_exists(AUDIO_DIRECTORY . '/' . $title)) {
			$rand = rand('0000', '9999');
			$title = $rand . $title;
		}
		
		return $title;
	}
	
	function registerMedia() {
		if (User::isAdmin()) {
			if ($this->av_area_id < 1) {
				$areaTitle = "Track Audio/Video: ";
				$allowed_extensions = MEDIA_EXTENSIONS_ALLOWED_AV;
				$display = "list";
				$ma = MediaArea::add(0, $areaTitle . $this->title, null, $allowed_extensions, $display);
				if (db::isError($ma)) {
					return $ma;
				}
				$ma->activate();
				$q = "update Release_Tracks set av_area_id = " . $ma->getID() . " where ID = {$this->ID}";
				$r = mysql_query($q);
				if (!$r) {
					return Error::MySQL();
				} else {
					return $r;
				}
				return $r;
			} else {
				return Error::create("A track with an ID of {$this->ID} is already registered.");
			}
		} else {
			return Error::create('Only an admin user may authorize a track for media.');
		}
	}
	
	function validateMediaOperation($opType = "ADD", $mediaObject = null) {
		// called automatically by the m2 functions that add media, when passed the object
		// opType allows us to distinguish between adding, editing, updating, etc... but most times
		// the same check will work for all operation types
		if ($opType == "RESCAN") {
			// non-admins can't delete, only deactivate
			if (!User::isAdmin()) {
				return Error::create('Only an admin user may rescan media.');
			} else {
				return true;
			}
		} else {
			if (!User::isAdmin()) {
				return Error::create('Only an admin user may add, delete, activate or deactivate track media.');
			} else {
				return true;
			}
		}
	}
} 

?>